package com.example.tms.controller;

import com.example.tms.bean.*;
import com.example.tms.mapper.*;
import com.example.tms.tools.GlobalParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 运单管理
 */
@RestController
public class WaybillController {

    private final WaybillMapper waybillMapper;
    private final OrderMapper orderMapper;
    private final CarVMapper carVMapper;
    private final OilfillMapper oilfillMapper;
    private final CstmrMapper cstmrMapper;
    private final AreaMapper areaMapper;
    private final RoadMapper roadMapper;
    private final CarMapper carMapper;
    private final WaybillVMapper waybillVMapper;

    @Autowired
    public WaybillController(WaybillMapper waybillMapper, OrderMapper orderMapper, CarVMapper carVMapper, OilfillMapper oilfillMapper, CstmrMapper cstmrMapper, AreaMapper areaMapper, RoadMapper roadMapper, WaybillVMapper waybillVMapper, CarMapper carMapper) {
        this.waybillMapper = waybillMapper;
        this.orderMapper = orderMapper;
        this.carVMapper = carVMapper;
        this.oilfillMapper = oilfillMapper;
        this.cstmrMapper = cstmrMapper;
        this.areaMapper = areaMapper;
        this.roadMapper = roadMapper;
        this.carMapper = carMapper;
        this.waybillVMapper = waybillVMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询运单信息列表
    @RequestMapping(value = "waybill", method = RequestMethod.GET)
    public ReturnInfo getWaybillList(@RequestParam(required = false, defaultValue = "") String khjc,
                                     @RequestParam(required = false, defaultValue = "") String khzjm,
                                     @RequestParam(required = false, defaultValue = "") String xlmc,
                                     @RequestParam(required = false, defaultValue = "") String xlzjm,
                                     @RequestParam(required = false, defaultValue = "") String qymc,
                                     @RequestParam(required = false, defaultValue = "") String qyzjm,
                                     @RequestParam(required = false, defaultValue = "") String ydh,
                                     @RequestParam(required = false, defaultValue = "") String ydzt,
                                     @RequestParam(required = false, defaultValue = "") String qsrq,
                                     @RequestParam(required = false, defaultValue = "") String jsrq,
                                     @RequestParam(required = false, defaultValue = "") String bd) {
        List<WaybillVMgmt> result = waybillVMapper.findAll((Root<WaybillVMgmt> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (!khjc.equals("")) {
                list.add(criteriaBuilder.like(root.get("khjc").as(String.class), "%" + khjc + "%"));
            }
            if (!khzjm.equals("")) {
                list.add(criteriaBuilder.like(root.get("khzjm").as(String.class), "%" + khzjm + "%"));
            }
            if (!xlmc.equals("")) {
                list.add(criteriaBuilder.like(root.get("xlmc").as(String.class), "%" + xlmc + "%"));
            }
            if (!xlzjm.equals("")) {
                list.add(criteriaBuilder.like(root.get("xlzjm").as(String.class), "%" + xlzjm + "%"));
            }
            if (!qymc.equals("")) {
                list.add(criteriaBuilder.like(root.get("qymc").as(String.class), "%" + qymc + "%"));
            }
            if (!qyzjm.equals("")) {
                list.add(criteriaBuilder.like(root.get("qyzjm").as(String.class), "%" + qyzjm + "%"));
            }
            if (!ydh.equals("")) {
                list.add(criteriaBuilder.like(root.get("ydh").as(String.class), "%" + ydh + "%"));
            }
            if (!ydzt.equals("")) {
                list.add(criteriaBuilder.like(root.get("ydzt").as(String.class), "%" + ydzt + "%"));
            }
            if (!qsrq.equals("")) {
                list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("ydrq").as(String.class), qsrq));
            }
            if (!jsrq.equals("")) {
                list.add(criteriaBuilder.lessThanOrEqualTo(root.get("ydrq").as(String.class), jsrq));
            }
            list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class), true));
            Predicate[] p = new Predicate[list.size()];
            Predicate predicate = criteriaBuilder.and(list.toArray(p));
            switch (bd){
                case "dd":
                    predicate = criteriaBuilder.and(predicate,criteriaBuilder.or(criteriaBuilder.equal(root.get("ydzt"),"待调度"), criteriaBuilder.equal(root.get("ydzt"),"待发车"), criteriaBuilder.equal(root.get("ydzt"),"已发车"), criteriaBuilder.equal(root.get("ydzt"),"调度_审核中")));
                    break;
                case "dj":
                    predicate = criteriaBuilder.and(predicate,criteriaBuilder.or(criteriaBuilder.equal(root.get("ydzt"),"已发车"), criteriaBuilder.equal(root.get("ydzt"),"已回车"), criteriaBuilder.equal(root.get("ydzt"),"登记_审核中")));
                    break;
                case "bz":
                    predicate = criteriaBuilder.and(predicate,criteriaBuilder.or(criteriaBuilder.equal(root.get("ydzt"),"已回车"), criteriaBuilder.equal(root.get("ydzt"),"已完成"), criteriaBuilder.equal(root.get("ydzt"),"报账_审核中")));
                    break;
                case "kj":
                    predicate = criteriaBuilder.and(predicate,criteriaBuilder.or(criteriaBuilder.equal(root.get("ydzt"),"快捷_已报"), criteriaBuilder.equal(root.get("ydzt"),"快捷_审核中")));
                    break;
                default:
                    break;
            }
            criteriaQuery.where(predicate);
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("ydrq")),criteriaBuilder.desc(root.get("khjc")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
    }

    //查询运单信息
    @RequestMapping(value = "waybill/{ydid}", method = RequestMethod.GET)
    public WaybillVMgmt getWaybillInfo(@PathVariable String ydid) {
        return waybillVMapper.findByYdid(ydid);
    }

    //车辆调度（车牌号）
    @RequestMapping(value = "waybill/cph", method = RequestMethod.PUT)
    public ReturnInfo updateWaybillCph(@RequestBody WaybillMgmt w){
        try{
            WaybillMgmt waybillMgmt = waybillMapper.findByYdid(w.getYdid());

            if(w.getClid().equals("")){
                waybillMgmt = WaybillMgmt.Waybill(waybillMgmt);
            }else {
                CarView carView = carVMapper.findByClidAndSfcz(w.getClid(),true);
                if(!waybillMgmt.getLeixing().equals("")){
                    waybillMgmt = WaybillMgmt.Waybill(waybillMgmt,carView);
                    waybillMgmt.setYdzt("待发车");
                }else {
                    waybillMgmt = WaybillMgmt.Waybill(waybillMgmt,carView);
                }

            }

            waybillMapper.saveAndFlush(waybillMgmt);
            logger.info("车辆调度成功"+w.getYdid());
            return ReturnInfo.info1("车辆调度成功！");
        }catch (NullPointerException e){
            logger.info("车辆调度失败"+w.getYdid());
            return ReturnInfo.info1("车辆调度失败！");
        }
    }
    //更新类型
    @RequestMapping(value = "waybill/type", method = RequestMethod.PUT)
    public ReturnInfo updateWaybillType(@RequestBody WaybillMgmt w){
        try{

            WaybillMgmt waybillMgmt = waybillMapper.findByYdid(w.getYdid());
                if(w.getLeixing().equals("")){
                    waybillMgmt.setYdzt("待调度");
                    waybillMgmt.setLeixing(w.getLeixing());
                }else {
                    if(waybillMgmt.getCph().equals("")){
                        waybillMgmt.setLeixing(w.getLeixing());
                    }else {
                        waybillMgmt.setYdzt("待发车");
                        waybillMgmt.setLeixing(w.getLeixing());
                    }
                }




            waybillMapper.saveAndFlush(waybillMgmt);
            logger.info("车辆调度成功"+w.getYdid());
            return ReturnInfo.info1("车辆调度成功！");
        }catch (NullPointerException e){
            logger.info("车辆调度失败"+w.getYdid());
            return ReturnInfo.info1("车辆调度失败！");
        }
    }

    //运单发车
    @RequestMapping(value = "waybill/{ydid}", method = RequestMethod.PUT)
    public ReturnInfo startWaybill(@PathVariable("ydid") String ydid){
        String b;
        if(waybillMapper.findByYdid(ydid)==null){
            b = "运单不存在";
        }else {
            WaybillMgmt waybillMgmt = waybillMapper.findByYdid(ydid);
            RoadInfo roadInfo = roadMapper.findByXlmcAndSfcz(waybillMgmt.getXlmc(),true);
            waybillMapper.startWaybill(ydid, GlobalParam.getSRq(), roadInfo.getYdj());//发车（更新油单价）
            b = "发车成功！";
//            CarInfo carInfo = carMapper.findByClid(waybillMgmt.getClid());
//            carInfo.setSffp("已分配");
            carMapper.updateCarfp(waybillMgmt.getCph());
//            OilfillInfo OilfillInfo = new OilfillInfo(waybillMgmt);//生成充油信息
//            try{
//                OilfillInfo.setFcrq(GlobalParam.getSRq());
//                oilfillMapper.save(OilfillInfo);
            logger.info("运单发车成功"+ydid);
//               // a = "生成充油信息成功！";
//            }catch (NullPointerException e){
//                logger.info("运单发车失败"+ydid);
//               // a = "生成充油信息失败！";
//            }
        }
        return ReturnInfo.info1(b);
    }

    //回车登记
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public List<Map<String,Object>> registerWaybill(@RequestBody WaybillMgmt w){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(w.getYdid()==null){
            map.put("ydid","0");
        }else if(waybillMapper.findByYdid(w.getYdid())==null){
            map.put("ydid","1");
        }
        list.add(map);
        if(map.isEmpty()){
            WaybillMgmt waybillMgmt = waybillMapper.findByYdid(w.getYdid());
            waybillMgmt = WaybillMgmt.register(waybillMgmt,w);
            waybillMapper.saveAndFlush(waybillMgmt);
            carMapper.updateBackCarfp(waybillMgmt.getCph());
            logger.info("回车登记成功"+w.getYdid());
        }
        return list;
    }

    //回车报账
    @RequestMapping(value = "account", method = RequestMethod.POST)
    public List<Map<String,Object>> accountWaybill(@RequestBody WaybillMgmt w){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(w.getYdid()==null){
            map.put("ydid","0");
        }else if(waybillMapper.findByYdid(w.getYdid())==null){
            map.put("ydid","1");
        }
        list.add(map);
        if(map.isEmpty()){
            WaybillMgmt waybillMgmt = waybillMapper.findByYdid(w.getYdid());
            waybillMgmt = WaybillMgmt.account(waybillMgmt, w);
            waybillMapper.saveAndFlush(waybillMgmt);
            logger.info("回车报账成功"+w.getYdid());
        }
        return list;
    }

    //快捷运单
    @RequestMapping(value = "shortcut", method = RequestMethod.POST)
    public List<Map<String,Object>> shortcutWaybill(@RequestBody WaybillMgmt waybillMgmt){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();

        list.add(map);
        if(map.isEmpty()) {
            String ydh = waybillMgmt.getYdrq().replaceAll("-","");
            long i = orderMapper.countByDdrq(waybillMgmt.getYdrq());
            OrderMgmt orderMgmt = new OrderMgmt(ydh,i);
            orderMapper.save(orderMgmt);
            waybillMgmt.setYdh(ydh+GlobalParam.getDdh(i));
            CstmrInfo cstmrInfo = cstmrMapper.findByKhid(waybillMgmt.getKhid());
            AreaInfo areaInfo = areaMapper.findByQyidAndSfcz(waybillMgmt.getQyid(),true);
            RoadInfo roadInfo = roadMapper.findByXlid(waybillMgmt.getXlid());
            waybillMgmt = WaybillMgmt.shortcut(waybillMgmt,cstmrInfo,areaInfo,roadInfo);
            waybillMapper.save(waybillMgmt);
            logger.info("新建快捷运单"+waybillMgmt.toString());
//            OilfillInfo OilfillInfo = new OilfillInfo(waybillMgmt);//生成充油信息
//            try{
//                OilfillInfo.setFcrq(GlobalParam.getSRq());
//                oilfillMapper.save(OilfillInfo);
//            }catch (NullPointerException e){
//                e.printStackTrace();
//            }
        }
        return list;
    }

}
